package com.asp.aspchain.account.controller;

import com.alibaba.fastjson.JSON;
import com.asp.aspchain.account.constants.ErrorCode;
import com.asp.aspchain.account.request.QryAccountReq;
import com.asp.aspchain.core.model.AppBaseModel;
import com.asp.aspchain.core.model.TocAccountModel;
import com.asp.aspchain.core.service.IAppBaseService;
import com.asp.aspchain.core.service.ITocAccountService;
import com.asp.aspchain.core.util.AjaxResult;
import com.asp.aspchain.core.util.BlogUtil;
import com.asp.aspchain.core.util.HttpRequestUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;


@RestController
@RequestMapping("/account")
public class QryAccountController {

	private final static Logger logger = Logger.getLogger(QryAccountController.class);
	@Autowired
	private IAppBaseService appBaseService;
	@Autowired
	private ITocAccountService tocAccountService;
	@Value("${server.port}")
	private String port;
	@Value("${server.context-path}")
	private String context;
	@Autowired
	private Validator validator;
	@Autowired
	private RedisTemplate redisTemplate;

	@PostMapping("/qryblance")
	@Transactional(isolation = Isolation.SERIALIZABLE)
	public AjaxResult AccountHandler(@RequestBody String json) {

		logger.info("=============AccountHandler开始=============");
		logger.info(json);
		// 接受前端请求记录内部日志
		BlogUtil.inlog(json, "", "account/qryblance/", "qryblance", "req");
		QryAccountReq accountReq = null;
		try {
			accountReq = JSON.parseObject(json, QryAccountReq.class);
		} catch (Exception e) {
			logger.error("创建账户接口解析错误：" + e.getMessage());
			e.printStackTrace();
		}

		// 参数校验
		AjaxResult result = checkPayParam(accountReq);
		if (result != null) {
			return result;
		}

		// 验证签名
		if (!sign(accountReq.getHmac())) {
			return new AjaxResult(ErrorCode.SIGN_ERROR, "签名验证失败", "签名验证失败");
		}

		// 生成url
		InetAddress addr = null;
		try {
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		String ip = "localhost:" + port;
		String url = null;
		AppBaseModel appBaseModel = appBaseService.selectOne(new EntityWrapper<AppBaseModel>().eq("appmark", accountReq.getAppmark()));
		String tokenType = appBaseModel.getTokentype();
		String accountType = appBaseModel.getAccounttype();
		String eoa = "00";
		String coa = "01";
		if (eoa.equals(accountType)) {
			url = "http://" + ip + context + "/account/eoa/qryblance";
		} else if (coa.equals(accountType)) {
			url = "http://" + ip + context + "/account/coa/" + tokenType + "/qryblance";
		}
		// 发送请求
		String resp = HttpRequestUtil.postJson(url, json);
		AjaxResult ajaxResult = JSON.parseObject(resp, AjaxResult.class);
		BlogUtil.inlog(resp, "", "account/qryblance/", "qryblance", "resp");
		logger.info("=============AccountHandler结束=============");
		return ajaxResult;
	}

	private AjaxResult checkPayParam(QryAccountReq accountReq) {
		// 参数校验
		Set<ConstraintViolation<QryAccountReq>> validate = validator.validate(accountReq);
		if (validate.size() > 0) {
			// 如果有错误，取出一条信息返回
			String message = validate.iterator().next().getMessage();
			return new AjaxResult(ErrorCode.PARAM_ERROR, message, message);
		}

		String appmark = accountReq.getAppmark();
		AppBaseModel appBaseModel = appBaseService.selectOne(new EntityWrapper<AppBaseModel>().eq("appmark", appmark));
		if (appBaseModel == null) {
			return new AjaxResult(ErrorCode.APP_NOT_EXIST, "不存在该app", "不存在该app");
		}
		String accountid = accountReq.getAccountid();
		TocAccountModel tocAccountModel = tocAccountService.selectById(accountid);
		if (tocAccountModel == null) {
			return new AjaxResult(ErrorCode.USER_NOT_EXIST, "不存在该用户", "不存在该用户");
		}
		if (tocAccountModel.getPassword() != null) {
			if (!tocAccountModel.getPassword().equals(accountReq.getPassword())) {
				return new AjaxResult(ErrorCode.PASSWORD_ERROR, "密码错误", "密码错误");
			}
		} else if (accountReq.getPassword() != null) {
			return new AjaxResult(ErrorCode.PASSWORD_ERROR, "密码错误", "密码错误");
		}

		return null;
	}

	private boolean sign(String hmac) {
		// TODO Auto-generated method stub
		return true;
	}

}
